package routers

import (
	"net/http"
	"path"
	"strings"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/plugins/cors"
)

//静态文件后缀
const staticFileExt = ".html|.js|.css|.png|.jpg|.jpeg|.ico|.otf"

func WebServerFilter(ctx *context.Context) {
	urlPath := ctx.Request.URL.Path
	if urlPath == "" || urlPath == "/" {
		urlPath = "index.html"
	}

	ext := path.Ext(urlPath)
	index := strings.Index(staticFileExt, ext)
	if index >= 0 {
		http.ServeFile(ctx.ResponseWriter, ctx.Request, "static/"+urlPath)
	}
}

func init() {
	beego.InsertFilter("/", beego.BeforeRouter, WebServerFilter)
	beego.InsertFilter("/*", beego.BeforeRouter, WebServerFilter)

	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowOrigins:     []string{"http://" + beego.AppConfig.String("front_end_domain") + ":" + beego.AppConfig.String("front_end_port")},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

}
